"""
AI自动开发MCP服务器
主服务器文件，包含所有MCP工具接口
"""

import asyncio
import sys
from pathlib import Path
from fastmcp import FastMCP

# 导入服务层
from project_service import project_service
from file_service import file_service
from environment_service import environment_service
from execution_service import execution_service

# 创建MCP服务器
mcp = FastMCP("AI Auto Development Server")


# ===== 项目管理工具 =====

@mcp.tool
def init_project(project_path: str, name: str, description: str, template_type: str = "basic") -> str:
    """
    初始化AI自动开发项目

    参数:
    - project_path: 项目路径（工作目录）
    - name: 项目名称
    - description: 项目描述
    - template_type: 项目模板类型 (basic/web_app/cli_tool/data_analysis)
    """
    try:
        result = project_service.init_project(project_path, name, description, template_type)

        if result['success']:
            response = f"✅ **项目初始化成功！**\n\n"
            response += f"📁 **项目路径**: `{result['project_path']}`\n"
            response += f"📝 **项目名称**: {name}\n"
            response += f"🏷️ **项目类型**: {result['template_type']}\n"
            response += f"🐍 **虚拟环境**: `{result['venv_path']}`\n"
            response += f"📋 **当前阶段**: {result['next_stage']}\n\n"

            response += "📄 **创建的文件**:\n"
            for file in result['files_created']:
                response += f"- `{file}`\n"

            response += f"\n💡 **下一步**: 开始需求沟通阶段，请编辑 `PROJECT_INFO.md` 文件完善项目需求。\n\n"
            response += "⚠️ **重要提醒**: \n"
            response += "- 所有Python命令将在项目虚拟环境中自动执行\n"
            response += "- 文件修改操作会自动记录到开发日志中\n"
            response += "- 请通过 `get_project_info()` 查看详细项目信息"

            return response
        else:
            return f"❌ **项目初始化失败**: {result['message']}"

    except Exception as e:
        return f"❌ **初始化异常**: {str(e)}"


@mcp.tool
def check_project_status(project_path: str) -> str:
    """
    检查项目状态和基本信息

    参数:
    - project_path: 项目路径
    """
    try:
        # 先检查是否已初始化
        if not project_service.is_project_initialized(project_path):
            return f"❌ **项目未初始化**: 路径 `{project_path}` 不是一个有效的AI自动开发项目"

        result = project_service.get_project_status(project_path)

        if result['success']:
            response = f"📊 **项目状态概览**\n\n"
            response += f"📁 **项目路径**: `{result['project_path']}`\n"
            response += f"📄 **文件数量**: {result['files_count']} 个\n"
            response += f"🕐 **最后修改**: {result['last_modified']}\n"
            response += f"🐍 **虚拟环境**: {result['venv_status']}\n\n"

            response += "📋 **关键文件**:\n"
            response += f"- 项目信息: `{Path(result['info_file']).name}`\n"
            response += f"- 开发日志: `{Path(result['log_file']).name}`\n"
            response += f"- 虚拟环境: `{Path(result['venv_path']).name}`\n\n"

            response += "💡 **可用操作**:\n"
            response += "- `get_project_info()` - 查看详细项目信息\n"
            response += "- `get_development_log()` - 查看开发日志\n"
            response += "- `log_stage_summary()` - 记录阶段总结"

            return response
        else:
            return f"❌ **获取状态失败**: {result['message']}"

    except Exception as e:
        return f"❌ **状态检查异常**: {str(e)}"


@mcp.tool
def get_project_info(project_path: str) -> str:
    """
    获取项目信息文件内容

    参数:
    - project_path: 项目路径
    """
    try:
        result = project_service.get_project_info(project_path)

        if result['success']:
            response = f"📄 **项目信息文件内容** (`{Path(result['file_path']).name}`)\n"
            response += f"🕐 **最后修改**: {result['last_modified']}\n\n"
            response += "---\n\n"
            response += result['content']

            return response
        else:
            return f"❌ **获取项目信息失败**: {result['message']}"

    except Exception as e:
        return f"❌ **获取信息异常**: {str(e)}"


@mcp.tool
def update_project_info(project_path: str, new_content: str) -> str:
    """
    更新项目信息文件内容

    ⚠️ 重要：必须严格遵循以下文件结构，否则系统功能将失效！

    必需的文件结构：
    ```markdown
    # {项目名称}

    ## 项目描述
    {详细描述}

    ## 项目信息
    - **项目名称**: {名称}
    - **项目类型**: {basic/web_app/cli_tool/data_analysis}
    - **创建时间**: {时间戳}
    - **Python版本**: {版本}
    - **虚拟环境**: ./venv/

    ## 开发阶段
    - **当前阶段**: {需求沟通/架构设计/代码实现/测试集成}
    - **完成阶段**: {已完成阶段}
    - **下一阶段**: {计划}

    ## 功能模块
    - [ ] 待实现功能
    - [x] 已完成功能

    ## 技术栈
    - **编程语言**: Python
    - **其他技术**: {根据项目类型}
    ```

    🚨 格式要求：
    - "- **当前阶段**: " 格式不能改变（系统依赖此格式）
    - 必须包含所有 ## 标题部分
    - 阶段名只能是：需求沟通/架构设计/代码实现/测试集成

    参数:
    - project_path: 项目路径
    - new_content: 新的项目信息内容（必须遵循上述格式）
    """
    try:
        if not project_service.is_project_initialized(project_path):
            return f"❌ **项目未初始化**: 无法更新项目信息"

        result = project_service.update_project_info(project_path, new_content)

        if result['success']:
            response = f"✅ **项目信息更新成功**\n\n"
            response += f"📄 **文件路径**: `{Path(result['file_path']).name}`\n"
            response += f"💾 **操作**: 内容已保存，变更已记录到开发日志\n\n"
            response += "💡 **提示**: 使用 `get_project_info()` 查看更新后的内容"
            return response
        else:
            return f"❌ **更新项目信息失败**: {result['message']}"

    except Exception as e:
        return f"❌ **更新异常**: {str(e)}"


@mcp.tool
def get_development_log(project_path: str, last_lines: int = 50) -> str:
    """
    获取开发日志内容

    参数:
    - project_path: 项目路径
    - last_lines: 显示最后N行（0表示显示全部）
    """
    try:
        project_dir = Path(project_path)
        log_file = project_dir / project_service.dev_log_file

        if not log_file.exists():
            return f"❌ **开发日志不存在**: `{log_file.name}`"

        content = log_file.read_text(encoding='utf-8')

        if last_lines > 0:
            lines = content.split('\n')
            if len(lines) > last_lines:
                content = '\n'.join(lines[-last_lines:])
                header = f"📜 **开发日志** (最后 {last_lines} 行)"
            else:
                header = f"📜 **开发日志** (完整内容)"
        else:
            header = f"📜 **开发日志** (完整内容)"

        response = f"{header}\n"
        response += f"📁 文件: `{log_file.name}`\n\n"
        response += "---\n\n"
        response += content

        return response

    except Exception as e:
        return f"❌ **获取开发日志异常**: {str(e)}"


@mcp.tool
def log_stage_summary(project_path: str, stage: str, summary: str) -> str:
    """
    记录开发阶段总结到日志（LLM主动调用）

    参数:
    - project_path: 项目路径
    - stage: 阶段名称（如：需求沟通、架构设计、代码实现、测试集成）
    - summary: 阶段总结（建议在总结中详细描述完成的工作和成果）
    """
    try:
        if not project_service.is_project_initialized(project_path):
            return f"❌ **项目未初始化**: 无法记录日志"

        success = project_service.log_stage_summary(project_path, stage, summary)

        if success:
            response = f"✅ **阶段总结已记录**\n\n"
            response += f"📋 **阶段**: {stage}\n"
            response += f"📝 **总结**: {summary}\n"
            response += f"\n💾 总结已追加到开发日志文件"
            return response
        else:
            return f"❌ **记录阶段总结失败**"

    except Exception as e:
        return f"❌ **记录总结异常**: {str(e)}"


@mcp.tool
def update_project_stage(project_path: str, new_stage: str) -> str:
    """
    更新项目开发阶段（在PROJECT_INFO.md中）
    注意！
    - 阶段名只能是：需求沟通/架构设计/代码实现/测试集成

    参数:
    - project_path: 项目路径
    - new_stage: 新的阶段名称
    """
    try:
        if not project_service.is_project_initialized(project_path):
            return f"❌ **项目未初始化**: 无法更新阶段"

        project_dir = Path(project_path)
        info_file = project_dir / project_service.project_info_file

        if not info_file.exists():
            return f"❌ **项目信息文件不存在**"

        # 读取现有内容
        content = info_file.read_text(encoding='utf-8')

        # 简单的字符串替换来更新当前阶段
        lines = content.split('\n')
        updated_lines = []
        stage_updated = False

        for line in lines:
            if '- **当前阶段**:' in line:
                updated_lines.append(f'- **当前阶段**: {new_stage}')
                stage_updated = True
            else:
                updated_lines.append(line)

        if stage_updated:
            # 写回文件
            info_file.write_text('\n'.join(updated_lines), encoding='utf-8')

            # 记录到开发日志
            project_service.log_file_change(project_path, 'PROJECT_INFO.md', 'EDIT', f'更新开发阶段为: {new_stage}')

            return f"✅ **开发阶段已更新**: {new_stage}"
        else:
            return f"❌ **未找到阶段信息行，无法更新**"

    except Exception as e:
        return f"❌ **更新阶段异常**: {str(e)}"


# ===== 文件操作工具 =====

@mcp.tool
def create_file(project_path: str, filepath: str, content: str = "", summary: str = "") -> str:
    """
    创建新文件

    参数:
    - project_path: 项目路径
    - filepath: 文件路径（相对于项目路径）
    - content: 文件内容
    - summary: 操作总结（可选）
    """
    try:
        result = file_service.create_file(project_path, filepath, content, summary)

        if result['success']:
            file_info = result['file_info']
            response = f"✅ **文件创建成功**\n\n"
            response += f"📄 **文件路径**: `{filepath}`\n"
            response += f"📊 **文件大小**: {file_info['size']} bytes\n"
            response += f"🕐 **创建时间**: {file_info['created']}\n"

            if summary:
                response += f"📝 **操作总结**: {summary}\n"

            response += f"\n💾 操作已记录到开发日志"
            return response
        else:
            return f"❌ **创建文件失败**: {result['message']}"

    except Exception as e:
        return f"❌ **创建异常**: {str(e)}"


@mcp.tool
def read_file(project_path: str, filepath: str) -> str:
    """
    读取文件内容

    参数:
    - project_path: 项目路径
    - filepath: 文件路径
    """
    try:
        result = file_service.read_file(project_path, filepath)

        if result['success']:
            file_info = result['file_info']
            response = f"📄 **文件内容** (`{filepath}`)\n\n"
            response += f"📊 **文件信息**:\n"
            response += f"- 大小: {file_info['size']} bytes\n"
            response += f"- 类型: {result['file_type']}\n"
            response += f"- 修改时间: {file_info['modified']}\n\n"
            response += "---\n\n"
            response += result['content']

            return response
        else:
            return f"❌ **读取文件失败**: {result['message']}"

    except Exception as e:
        return f"❌ **读取异常**: {str(e)}"


@mcp.tool
def edit_file(project_path: str, filepath: str, content: str, summary: str = "") -> str:
    """
    编辑文件内容（覆盖）

    参数:
    - project_path: 项目路径
    - filepath: 文件路径
    - content: 新的文件内容
    - summary: 操作总结（可选）
    """
    try:
        result = file_service.edit_file(project_path, filepath, content, summary)

        if result['success']:
            file_info = result['file_info']
            response = f"✅ **文件编辑成功**\n\n"
            response += f"📄 **文件路径**: `{filepath}`\n"
            response += f"📊 **文件大小**: {file_info['size']} bytes\n"
            response += f"🕐 **修改时间**: {file_info['modified']}\n"

            if 'backup_path' in result:
                response += f"🔄 **备份文件**: `{Path(result['backup_path']).name}`\n"

            if summary:
                response += f"📝 **操作总结**: {summary}\n"

            response += f"\n💾 操作已记录到开发日志"
            return response
        else:
            return f"❌ **编辑文件失败**: {result['message']}"

    except Exception as e:
        return f"❌ **编辑异常**: {str(e)}"


@mcp.tool
def delete_file(project_path: str, filepath: str, summary: str = "") -> str:
    """
    删除文件

    参数:
    - project_path: 项目路径
    - filepath: 文件路径
    - summary: 操作总结（可选）
    """
    try:
        result = file_service.delete_file(project_path, filepath, summary)

        if result['success']:
            file_info = result['deleted_file_info']
            response = f"✅ **文件删除成功**\n\n"
            response += f"📄 **已删除文件**: `{filepath}`\n"
            response += f"📊 **文件大小**: {file_info['size']} bytes\n"

            if 'backup_path' in result:
                response += f"🔄 **备份文件**: `{Path(result['backup_path']).name}`\n"

            if summary:
                response += f"📝 **操作总结**: {summary}\n"

            response += f"\n💾 操作已记录到开发日志"
            return response
        else:
            return f"❌ **删除文件失败**: {result['message']}"

    except Exception as e:
        return f"❌ **删除异常**: {str(e)}"


@mcp.tool
def backup_file(project_path: str, filepath: str) -> str:
    """
    手动备份文件

    参数:
    - project_path: 项目路径
    - filepath: 文件路径
    """
    try:
        result = file_service.backup_file_manual(project_path, filepath)

        if result['success']:
            response = f"✅ **文件备份成功**\n\n"
            response += f"📄 **原文件**: `{filepath}`\n"
            response += f"🔄 **备份文件**: `{Path(result['backup_path']).name}`\n"
            response += f"\n💾 操作已记录到开发日志"
            return response
        else:
            return f"❌ **备份文件失败**: {result['message']}"

    except Exception as e:
        return f"❌ **备份异常**: {str(e)}"


@mcp.tool
def search_content(project_path: str, query: str, extension: str = None, max_results: int = 20) -> str:
    """
    全局内容搜索

    参数:
    - project_path: 项目路径
    - query: 搜索查询
    - extension: 文件扩展名（如 '.py' 或 '.md'，默认搜索.py和.md文件）
    - max_results: 最大结果数量
    """
    try:
        if extension is None:
            file_extensions = None
        else:
            file_extensions = extension

        result = file_service.search_content_global(project_path, query, file_extensions, max_results)

        if result['success']:
            response = f"🔍 **内容搜索结果**\n\n"
            response += f"📝 **搜索查询**: `{query}`\n"
            response += f"📊 **结果统计**: {result['results_count']} 个匹配，搜索了 {result['files_searched']} 个文件\n"
            if extension:
                response += f"📁 **搜索扩展名**: {extension}\n\n"
            else:
                response += f"📁 **搜索扩展名**: .py, .md\n\n"

            if result['results_count'] > 0:
                response += "---\n\n"
                for i, match in enumerate(result['results'][:max_results], 1):
                    response += f"**{i}. `{match['file_path']}`** (第{match['line_number']}行)\n"
                    response += f"```\n{match['line_content']}\n```\n\n"

                if result['results_count'] > max_results:
                    response += f"... 还有 {result['results_count'] - max_results} 个结果未显示\n"
            else:
                response += "🔍 **未找到匹配内容**"

            return response
        else:
            return f"❌ **搜索失败**: {result['message']}"

    except Exception as e:
        return f"❌ **搜索异常**: {str(e)}"


@mcp.tool
def search_functions(project_path: str, query: str, file_path: str = None) -> str:
    """
    搜索Python函数定义

    参数:
    - project_path: 项目路径
    - query: 函数名搜索查询
    - file_path: 指定文件路径（可选，None表示搜索所有Python文件）
    """
    try:
        result = file_service.search_functions(project_path, query, file_path)

        if result['success']:
            response = f"🔍 **函数搜索结果**\n\n"
            response += f"📝 **搜索查询**: `{query}`\n"
            response += f"📊 **结果统计**: {result['results_count']} 个函数，搜索了 {result['files_searched']} 个Python文件\n"
            response += f"🎯 **搜索范围**: {result['search_scope']}\n\n"

            if result['results_count'] > 0:
                response += "---\n\n"
                for i, func in enumerate(result['functions'], 1):
                    response += f"**{i}. `{func['name']}()`** - `{func['file_path']}`\n"
                    response += f"📍 第{func['line_start']}行\n"
                    response += f"📝 签名: `{func['signature']}`\n"

                    if func['docstring']:
                        response += f"📖 说明: {func['docstring'][:100]}{'...' if len(func['docstring']) > 100 else ''}\n"

                    response += f"```python\n{func['full_definition']}\n```\n\n"
            else:
                response += "🔍 **未找到匹配函数**"

            return response
        else:
            return f"❌ **函数搜索失败**: {result['message']}"

    except Exception as e:
        return f"❌ **函数搜索异常**: {str(e)}"


@mcp.tool
def analyze_directory(project_path: str, target_path: str = ".", max_depth: int = 3) -> str:
    """
    分析目录结构

    参数:
    - project_path: 项目路径
    - target_path: 目标路径（相对于项目路径，默认为当前目录）
    - max_depth: 最大深度
    """
    try:
        result = file_service.analyze_directory_structure(project_path, target_path, max_depth)

        if result['success']:
            stats = result['statistics']
            response = f"📊 **目录结构分析**\n\n"
            response += f"📁 **分析路径**: `{result['target_path']}`\n"
            response += f"🎯 **最大深度**: {result['max_depth']}\n\n"

            response += f"📈 **统计信息**:\n"
            response += f"- 总文件数: {stats['total_files']}\n"
            response += f"- 总大小: {stats['total_size']:,} bytes\n"
            response += f"- 最大深度: {stats['max_depth_found']}\n\n"

            if stats['file_types']:
                response += f"📋 **文件类型分布**:\n"
                for ext, count in stats['file_types'].items():
                    response += f"- {ext}: {count} 个\n"
                response += "\n"

            if result.get('files'):
                response += f"📄 **文件列表** (前100个):\n"
                for file_info in result['files'][:100]:
                    indent = "  " * file_info['depth']
                    response += f"{indent}📄 {file_info['name']} ({file_info['size']} bytes)\n"

                if len(result['files']) > 100:
                    response += f"... 还有 {len(result['files']) - 100} 个文件未显示\n"

            return response
        else:
            return f"❌ **目录分析失败**: {result['message']}"

    except Exception as e:
        return f"❌ **分析异常**: {str(e)}"


# ===== 环境管理工具 =====

@mcp.tool
def install_package(project_path: str, package_name: str, version: str = None) -> str:
    """
    在项目虚拟环境中安装Python包

    参数:
    - project_path: 项目路径
    - package_name: 包名
    - version: 版本号（可选，如 '2.1.0'）
    """
    try:
        result = environment_service.install_package(project_path, package_name, version)

        if result['success']:
            response = f"✅ **包安装成功**\n\n"
            response += f"📦 **包名**: {result['package_name']}\n"

            if result['version']:
                response += f"🏷️ **版本**: {result['version']}\n"
            else:
                response += f"🏷️ **版本**: 最新版本\n"

            response += f"\n💾 操作已记录到开发日志\n"
            response += f"📋 requirements.txt 已自动更新"

            return response
        else:
            return f"❌ **包安装失败**: {result['message']}\n\n**错误信息**: {result.get('error', '未知错误')}"

    except Exception as e:
        return f"❌ **安装异常**: {str(e)}"


@mcp.tool
def uninstall_package(project_path: str, package_name: str) -> str:
    """
    从项目虚拟环境中卸载Python包

    参数:
    - project_path: 项目路径
    - package_name: 包名
    """
    try:
        result = environment_service.uninstall_package(project_path, package_name)

        if result['success']:
            response = f"✅ **包卸载成功**\n\n"
            response += f"📦 **包名**: {result['package_name']}\n"
            response += f"\n💾 操作已记录到开发日志\n"
            response += f"📋 requirements.txt 已自动更新"

            return response
        else:
            return f"❌ **包卸载失败**: {result['message']}\n\n**错误信息**: {result.get('error', '未知错误')}"

    except Exception as e:
        return f"❌ **卸载异常**: {str(e)}"


@mcp.tool
def list_packages(project_path: str) -> str:
    """
    列出项目虚拟环境中已安装的包

    参数:
    - project_path: 项目路径
    """
    try:
        result = environment_service.list_installed_packages(project_path)
        response = ""

        if result['success']:
            if 'packages' in result:
                packages = result['packages']
                response = f"📦 **已安装包列表**\n\n"
                response += f"📊 **包数量**: {result['packages_count']}\n\n"

                if packages:
                    response += "---\n\n"
                    for i, pkg in enumerate(packages[:20], 1):
                        response += f"{i:2d}. **{pkg['name']}** - `{pkg['version']}`\n"

                    if len(packages) > 20:
                        response += f"\n... 还有 {len(packages) - 20} 个包未显示\n"
                else:
                    response += "📋 虚拟环境中暂无已安装的包"

            return response
        else:
            return f"❌ **获取包列表失败**: {result['message']}"

    except Exception as e:
        return f"❌ **列表异常**: {str(e)}"


@mcp.tool
def install_from_requirements(project_path: str, requirements_file: str = "requirements.txt") -> str:
    """
    从requirements.txt批量安装包

    参数:
    - project_path: 项目路径
    - requirements_file: requirements文件名（默认为requirements.txt）
    """
    try:
        result = environment_service.install_from_requirements(project_path, requirements_file)

        if result['success']:
            response = f"✅ **批量安装成功**\n\n"
            response += f"📋 **源文件**: `{result['requirements_file']}`\n"
            response += f"💾 **操作**: 已从requirements文件安装所有依赖包\n"
            response += f"\n💾 操作已记录到开发日志"

            return response
        else:
            return f"❌ **批量安装失败**: {result['message']}\n\n**错误信息**: {result.get('error', '未知错误')}"

    except Exception as e:
        return f"❌ **批量安装异常**: {str(e)}"


@mcp.tool
def generate_requirements(project_path: str) -> str:
    """
    生成requirements.txt文件

    参数:
    - project_path: 项目路径
    """
    try:
        result = environment_service.generate_requirements_file(project_path)

        if result['success']:
            response = f"✅ **requirements.txt 生成成功**\n\n"
            response += f"📄 **文件路径**: `requirements.txt`\n"
            response += f"📊 **包数量**: {result['packages_count']}\n"
            response += f"💾 **操作**: 已记录到开发日志"

            return response
        else:
            return f"❌ **生成requirements.txt失败**: {result['message']}"

    except Exception as e:
        return f"❌ **生成异常**: {str(e)}"


# ===== 执行服务工具 =====

@mcp.tool
async def execute_command(project_path: str, command: str, timeout: int = 30) -> str:
    """
    在项目虚拟环境中执行命令

    参数:
    - project_path: 项目路径
    - command: 要执行的命令
    - timeout: 超时时间（秒，默认30秒）
    """
    try:
        result = await execution_service.execute_command(project_path, command, timeout)

        if result['success']:
            response = f"✅ **命令执行成功**\n\n"
            response += f"🔧 **命令**: `{result['command']}`\n"
            response += f"📁 **工作目录**: `{Path(result['working_dir']).name}`\n"
            response += f"🔴 **返回码**: {result['returncode']}\n"

            if result['stdout']:
                response += f"\n📤 **标准输出**:\n```\n{result['stdout'].strip()}\n```\n"

            if result['stderr']:
                response += f"\n⚠️ **标准错误**:\n```\n{result['stderr'].strip()}\n```\n"

            response += f"\n💾 操作已记录到开发日志"
            return response
        else:
            error_msg = result.get('message', '未知错误')
            response = f"❌ **命令执行失败**: {error_msg}\n\n"
            response += f"🔧 **命令**: `{result.get('command', command)}`\n"

            if result.get('timeout'):
                response += f"⏰ **原因**: 执行超时 ({timeout}秒)"
            elif result.get('stderr'):
                response += f"⚠️ **错误输出**:\n```\n{result['stderr'].strip()}\n```"

            return response

    except Exception as e:
        return f"❌ **执行异常**: {str(e)}"


@mcp.tool
async def execute_python(project_path: str, code: str, timeout: int = 30) -> str:
    """
    临时执行简单的Python测试代码（在项目虚拟环境中）

    ！注意！
    此方法支持简单python代码的无状态执行，禁止使用此方法去运行本地python文件

    参数:
    - project_path: 项目路径
    - code: Python代码
    - timeout: 超时时间（秒，默认30秒）
    """
    try:
        result = await execution_service.execute_python_code(project_path, code, timeout)

        if result['success']:
            response = f"✅ **Python代码执行成功**\n\n"
            response += f"📝 **代码行数**: {len(code.split(chr(10)))}\n"
            response += f"🔴 **返回码**: {result['returncode']}\n"

            if result['stdout']:
                response += f"\n📤 **输出结果**:\n```\n{result['stdout'].strip()}\n```\n"

            if result['stderr']:
                response += f"\n⚠️ **错误信息**:\n```\n{result['stderr'].strip()}\n```\n"

            response += f"\n💾 操作已记录到开发日志"
            return response
        else:
            error_msg = result.get('message', '未知错误')
            response = f"❌ **Python代码执行失败**: {error_msg}\n\n"

            if result.get('stderr'):
                response += f"⚠️ **错误输出**:\n```\n{result['stderr'].strip()}\n```"

            return response

    except Exception as e:
        return f"❌ **执行异常**: {str(e)}"


@mcp.tool
async def start_server_process(project_path: str, command: str, process_name: str, output_file: str = None) -> str:
    """
    启动长时间运行的服务器进程

    参数:
    - project_path: 项目路径
    - command: 启动命令
    - process_name: 进程名称（用于后续管理）
    - output_file: 输出重定向文件名（可选）
    """
    try:
        result = await execution_service.start_long_process(project_path, command, process_name, output_file)

        if result['success']:
            response = f"✅ **服务器进程启动成功**\n\n"
            response += f"📋 **进程名称**: `{result['process_name']}`\n"
            response += f"🆔 **进程ID**: {result['pid']}\n"
            response += f"🔧 **启动命令**: `{result['command']}`\n"

            if result['output_file']:
                response += f"📄 **输出文件**: `{result['output_file']}`\n"
                response += f"\n💡 **提示**: 使用 `read_process_output()` 查看实时输出"

            response += f"\n🎯 **管理操作**:\n"
            response += f"- `terminate_process('{process_name}')` - 终止进程\n"
            response += f"- `list_active_processes()` - 查看进程状态"

            return response
        else:
            return f"❌ **启动进程失败**: {result['message']}"

    except Exception as e:
        return f"❌ **启动异常**: {str(e)}"


@mcp.tool
def terminate_process(process_name: str) -> str:
    """
    终止指定的长时间运行进程

    参数:
    - process_name: 进程名称
    """
    try:
        result = execution_service.terminate_process(process_name)

        if result['success']:
            response = f"✅ **进程终止成功**\n\n"
            response += f"📋 **进程名称**: `{result['process_name']}`\n"
            response += f"⏱️ **运行时间**: {result['run_time']}\n"

            if result['output_file']:
                response += f"📄 **输出文件**: `{result['output_file']}`\n"

            response += f"\n💾 操作已记录到开发日志"
            return response
        else:
            return f"❌ **终止进程失败**: {result['message']}"

    except Exception as e:
        return f"❌ **终止异常**: {str(e)}"


@mcp.tool
def list_active_processes() -> str:
    """
    列出所有活跃的长时间运行进程
    """
    try:
        result = execution_service.list_active_processes()

        if result['success']:
            if result['processes_count'] > 0:
                response = f"📋 **活跃进程列表**\n\n"
                response += f"📊 **进程数量**: {result['processes_count']}\n\n"
                response += "---\n\n"

                for i, proc in enumerate(result['processes'], 1):
                    response += f"**{i}. {proc['name']}** {proc['status_emoji']}\n"
                    response += f"   - 状态: {proc['status']}\n"
                    response += f"   - PID: {proc['pid']}\n"
                    response += f"   - 启动时间: {proc['start_time']}\n"
                    response += f"   - 运行时间: {proc['run_time']}\n"
                    response += f"   - 命令: `{proc['command']}`\n"

                    if proc['output_file']:
                        response += f"   - 输出文件: `{proc['output_file']}`\n"

                    if proc['returncode'] is not None:
                        response += f"   - 返回码: {proc['returncode']}\n"

                    response += "\n"

                response += "💡 **管理提示**: 使用 `cleanup_zombie_processes()` 清理已结束的进程"
            else:
                response = result['message']

            return response
        else:
            return f"❌ **获取进程列表失败**: {result['message']}"

    except Exception as e:
        return f"❌ **列表异常**: {str(e)}"


@mcp.tool
def cleanup_zombie_processes() -> str:
    """
    清理已结束的僵尸进程
    """
    try:
        result = execution_service.cleanup_zombie_processes()

        if result['success']:
            if result['cleaned_count'] > 0:
                response = f"🧹 **僵尸进程清理完成**\n\n"
                response += f"📊 **清理数量**: {result['cleaned_count']} 个\n"
                response += f"📋 **清理列表**: {', '.join(result['cleaned_processes'])}\n"
                response += f"\n✨ 所有僵尸进程已从管理列表中移除"
            else:
                response = f"✨ **没有发现僵尸进程**\n\n所有活跃进程状态正常"

            return response
        else:
            return f"❌ **清理失败**: {result['message']}"

    except Exception as e:
        return f"❌ **清理异常**: {str(e)}"


@mcp.tool
def read_process_output(project_path: str, output_file: str, last_lines: int = 10) -> str:
    """
    读取进程输出文件内容

    参数:
    - project_path: 项目路径
    - output_file: 输出文件名
    - last_lines: 读取最后N行（0表示读取全部）
    """
    try:
        result = execution_service.read_process_output(project_path, output_file, last_lines)

        if result['success']:
            response = f"📄 **进程输出文件** (`{result['output_file']}`)\n\n"
            response += f"📊 **文件大小**: {result['file_size']} bytes\n"
            response += f"📋 **显示内容**: {result['display_info']}\n\n"
            response += "---\n\n"

            if result['content'].strip():
                response += result['content']
            else:
                response += "📝 文件内容为空"

            return response
        else:
            return f"❌ **读取输出失败**: {result['message']}"

    except Exception as e:
        return f"❌ **读取异常**: {str(e)}"


# ===== 资源定义 =====

@mcp.resource("ai-dev://info")
def server_info() -> str:
    """AI自动开发服务器信息"""
    return f"""🤖 AI自动开发MCP服务器
🐍 Python版本: {sys.version.split()[0]}
🔧 当前模块: 项目管理层 + 文件操作层

📋 **可用工具 (项目管理)**:
• init_project() - 初始化新项目
• check_project_status() - 检查项目状态
• get_project_info() - 获取项目信息
• update_project_info() - 更新项目信息文件
• get_development_log() - 查看开发日志
• log_stage_summary() - 记录阶段总结
• update_project_stage() - 更新开发阶段

📋 **可用工具 (文件操作)**:
• create_file() - 创建新文件
• read_file() - 读取文件内容
• edit_file() - 编辑文件内容
• delete_file() - 删除文件  
• backup_file() - 手动备份文件
• search_content() - 全局内容搜索（支持指定文件扩展名）
• search_functions() - 搜索Python函数定义
• analyze_directory() - 分析目录结构

📋 **可用工具 (环境管理)**:
- install_package() - 安装Python包
- uninstall_package() - 卸载Python包
- list_packages() - 列出已安装包
- install_from_requirements() - 从requirements.txt批量安装
- generate_requirements() - 生成requirements.txt文件

📋 **可用工具 (执行服务)**:
- execute_command() - 执行系统命令（虚拟环境中）
- execute_python() - 执行Python代码
- start_server_process() - 启动长时间运行进程
- terminate_process() - 终止指定进程
- list_active_processes() - 列出活跃进程
- cleanup_zombie_processes() - 清理僵尸进程
- read_process_output() - 读取进程输出文件

🏗️ **支持的项目模板**:
• basic - 基础Python项目
• web_app - Flask Web应用项目  
• cli_tool - 命令行工具项目
• data_analysis - 数据分析项目

📋 **开发阶段流程**:
1. 需求沟通 - 与用户讨论需求，完善项目信息
2. 架构设计 - 设计项目结构和模块划分  
3. 代码实现 - 迭代开发功能模块
4. 测试集成 - 测试和完善项目功能

💡 **使用建议**:
1. 使用 init_project() 在工作目录创建项目
2. 使用 get_project_info() 查看项目详细信息
3. 使用 create_file()/edit_file() 管理项目文件
4. 使用 search_content()/search_functions() 搜索代码
5. 使用 log_stage_summary() 记录重要的阶段成果

🔮 **即将支持**: 代码执行、环境管理等功能
"""


# ===== 服务器启动 =====

async def main():
    """启动AI自动开发MCP服务器"""
    print("🤖 AI自动开发MCP服务器启动中...")
    print("📋 当前功能: 项目管理层 + 文件操作层 + 环境管理层 + 执行服务层")
    print("🔧 支持操作: 项目管理、文件CRUD、包管理、命令执行、进程管理")
    print("🌐 传输模式: SSE")
    print("🔗 连接地址: http://localhost:3003")
    print()
    print("✨ 服务器就绪，可以开始AI自动开发！")

    await mcp.run_async(
        transport="sse",
        host="localhost",
        port=3003
    )


if __name__ == "__main__":
    asyncio.run(main())